<template>
	<view class="wrap">
		<view class="top">
			<view class="item">
				<view class="left">收货人</view>
				<input v-model="addressData.contacts" maxlength="5" type="text" placeholder-class="line" placeholder="请填写收货人姓名" />
			</view>
			<view class="item">
				<view class="left">手机号码</view>
				<input v-model="addressData.phone" maxlength="11" type="text" placeholder-class="line" placeholder="请填写收货人手机号" />
			</view>
			<view class="item" @tap="showRegionPicker">
				<view class="left">所在地区</view>
				<input v-model="cityText" disabled type="text" placeholder-class="line" placeholder="省市区县、乡镇等" />
			</view>
			<view class="item address">
				<view class="left">详细地址</view>
				<textarea @click="detailAddressClick" disabled v-model="addressData.address" type="text"
					placeholder-class="line" placeholder="街道、楼牌等" />
			</view>
		</view>
		<view class="bottom">
			<view class="default">
				<view class="left">
					<view class="set">设置默认地址</view>
					<view class="tips">提醒：每次下单会默认推荐该地址</view>
				</view>
				<view class="right">
					<u-switch activeColor="#FF4110" :activeValue="true" :inactiveValue="false"
						v-model="addressData.isDef" />
				</view>
			</view>
		</view>

		<view class="addSite">
			<u-button shape="circle" type="primary" text="保存" @click="submit"></u-button>
		</view>
	</view>
	<cityPicker v-model="show" @confirmCityPicker="confirmCityPicker"></cityPicker>
</template>

<script setup>
	import API from "@/api/index.js"
	import cityPicker from "@/components/cityPicker/index.vue"
	import {
		MAP_KEY
	} from "@/config/app.js"
	import {
		ref
	} from "vue"
	import {
		toast,
		test
	} from "@/uni_modules/uview-plus";
	import {
		findNameByCodeWithPath
	} from "@/utils/index.js"
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const addressData = ref({
		contacts: '',
		phone: '',
		cityCode: '',
		address: '',
		lat: '',
		lng: '',
		province:'',
		city :'',
		isDef: false
	})

	onLoad((options) => {
		if (options.isEdit == 1) {
			isEdit.value=1
			const editData = JSON.parse(options.editData)
			console.log("editData",editData);
			for (const key in addressData.value) {
				addressData.value[key] = editData[key]
			}
			addressData.value.id = editData.id
			// cityText.value = findNameByCodeWithPath(addressData.value.cityCode).path.join('/')
			cityText.value = editData.province+'/'+editData.city
		}
	})
	const show = ref(false)
	const isEdit = ref(0)
	// 显示地址文本
	const cityText = ref('')
	const detailAddressClick = () => {
		if (cityText.value == '' || addressData.value.cityCode == '') return toast('请先选择所在地区')
		const cityName = cityText.value.split('/').join('')
		// 调用高德获取经纬度
		uni.request({
			url: `https://restapi.amap.com/v3/geocode/geo?key=${MAP_KEY}&city=${addressData.value.cityCode}&address=${cityName}`,
			success(res) {
				// 	经度，纬度
				const location = res.data.geocodes[0].location.split(',')
				// 根据选择城市经纬度再去选择地址结果更为准确
				uni.chooseLocation({
					longitude: location[0],
					latitude: location[1],
					success(data) {
						addressData.value.address = data.name
						addressData.value.lat = data.latitude
						addressData.value.lng = data.longitude
					},
					fail(err) {
						console.log('err: ', err);
					}
				})
			}
		})

	}


	const showRegionPicker = () => {
		show.value = true;
	}

	const confirmCityPicker = (data) => {
		addressData.value.address = ''
		addressData.value.lat = ''
		addressData.value.lng = ''
		cityText.value = `${data[0].name}/${data[1].name}/${data[2].name}`
		addressData.value.province = `${data[0].name}/${data[1].name}`
		addressData.value.city = `${data[2].name}`
		addressData.value.cityCode = data[2].code
		show.value = false;
	}

	// 保存
	const submit = async () => {
		const rules = [{
				key: 'name',
				text: '请填写收货人'
			},
			{
				key: 'phone',
				text: '请填写正确的手机号',
				test: 'mobile'
			},
			{
				key: 'cityCode',
				text: '请填写所在地区'
			},
			{
				key: 'address',
				text: '请选择详细地址'
			}
		]

		for (let item of rules) {
			if (addressData.value[item.key] == '') return toast(item.text)
			if (item.test && !test[item.test](addressData.value[item.key])) return toast(item.text)
		}

		console.log(addressData.value)
		let id = await API.uuid()
		let user = uni.getStorageSync('userInfo')
		let data = JSON.stringify({
			// 后台修改信息 必要字段------------------
			// Id:user.id?user.id:id.data,
			Id:'',
			RegisterUserId :user.id,
			RegisterDeptId :user.deptId,
			RegisteTime :user.registeTime,
			editUserId:userInfo.id,
			EditTime : +new Date(),
			RegisterInfo :null,
			EditUserInfo :null,
			RegisterDept :null,
			// 地址管理必传字段--------------------------
			Address :addressData.value.address,
			id:addressData.value.id?addressData.value.id:'',
			// userAddress :addressData.value.address,
			Lat :uni.getStorageSync('location').lat,
			Lng :uni.getStorageSync('location').lng,
			UserId :user.id,
			IsDef :addressData.value.isDef,
			Phone :addressData.value.phone,
			Province :addressData.value.province,
			Contacts :addressData.value.contacts,
			City :addressData.value.city,
			cityCode:addressData.value.cityCode
		})
		let res={}
		// 编辑
		if(isEdit.value==1){
			res = await API.putUserAddress(data)
			console.log("putUserAddress res",res);
		}else{
			// 添加
			 res = await API.addUserAddress(data)
			console.log("addUserAddress res",res);
		}

		uni.showToast({
			title: res.msg,
			icon: "none"
		})
		setTimeout(()=>{
			uni.navigateBack()
		},2000)
	}
</script>

<style lang="scss" scoped>
	.line {
		color: $u-light-color;
		font-size: 28rpx;
	}

	.wrap {
		background-color: #f2f2f2;

		.top {
			background-color: #ffffff;
			border-top: solid 2rpx $u-border-color;
			padding: 22rpx;

			.item {
				display: flex;
				font-size: 28rpx;
				line-height: 100rpx;
				align-items: center;
				// border-bottom: solid 2rpx $u-border-color;

				.left {
					width: 180rpx;
				}

				input {
					text-align: left;
				}
			}

			.address {
				padding: 20rpx 0;

				textarea {
					// width: 100%;
					height: 150rpx;
					background-color: #f7f7f7;
					line-height: 60rpx;
					margin: 40rpx auto;
					padding: 20rpx;
				}
			}

			.site-clipboard {
				padding-right: 40rpx;

				textarea {
					// width: 100%;
					height: 150rpx;
					background-color: #f7f7f7;
					line-height: 60rpx;
					margin: 40rpx auto;
					padding: 20rpx;
				}

				.clipboard {
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 26rpx;
					color: $u-tips-color;
					height: 80rpx;

					.icon {
						margin-top: 6rpx;
						margin-left: 10rpx;
					}
				}
			}
		}

		.bottom {
			margin-top: 20rpx;
			padding: 20rpx;
			background-color: #ffffff;
			font-size: 28rpx;

			.default {
				display: flex;
				justify-content: space-between;
				line-height: 64rpx;

				.tips {
					font-size: 24rpx;
				}

				.right {}
			}
		}
	}

	.addSite {
		margin-top: 40rpx;
		padding: 20px;
	}
</style>